;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Sales.Client", [])
        .controller("ClientCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$timeout", "$filter", "UserContextService", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $timeout, $filter, UserContextService) {
            $scope.isOrNotEnum = {
                Is: 1,
                No: 0
            };
            $scope.activeFlag = [true, false, false, false, false];
            $scope.markInfo = {
                allChecked: false
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.receiveInfoPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.maintenVehPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.boundObj = {};
            $scope.vehObj = {
                isDisable: 0,
                warrantStatus: 1
            }; // 车辆列表对象
            $scope.submitted = false;
            $scope.condition = { allQueryFlag: true };
            $scope.vehCondition = {};
            $scope.receiveInfoCondition = {};
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false
            };
            $scope.dataList = [];
            $scope.maintenVehList = []; // 客户用车了列表
            $scope.receiveInfoDataList = [];
            $scope.exportParam = {
                allUrl: ybHttp.RequestUrl("device", "/dealerVehicle/exportAll"),
                dealerVehiclesExportUrl: ybHttp.RequestUrl("device", "/companyDealer/exportDealerVehicles")
            };
            $scope.detailInfo = {
                locked: 0,
                bigClientFlag: 0,
                isStorage: 0,
                normalFlag: 1,
                jckPriceFlag: 0,
                isCompetingDealer: 0,
                isConfigMaterials: 0,
            };
            $scope.receiveInfo = {};
            $scope.tabFlag = {};
            var tabFlag = {
                0: "新增",
                1: "编辑"
            };
            $scope.receiveInfoTabFlag = {};
            $scope.vehTabFlag = {};
            var receiveInfoTabFlag = {
                0: "新增",
                1: "编辑"
            };
            $scope.dealerClass = {};
            $scope.tbConf = {
                fixedWidth: 300,
                scrollWidth: 1420,
                tableCol: [
                    {
                        type: "",
                        name: "客户编号",
                        width: 150,
                        dataField: "dealerCode",
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户名称",
                        width: 150,
                        dataField: "companyName",
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        name: "登录账号",
                        width: 150,
                        dataField: "platOrgId",
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "客户分级",
                        width: 150,
                        dataField: "dealerLevelName",
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户代码",
                        width: 150,
                        dataField: "dealerOrgId",
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "价格组",
                        width: 70,
                        dataField: "priceGroup",
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户状态",
                        width: 100,
                        dataField: "normalFlagF",
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户分类",
                        width: 100,
                        dataField: "dealerClassName",
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户简称",
                        width: 150,
                        dataField: "shortName",
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户地址",
                        width: 150,
                        dataField: "address",
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "联系人",
                        width: 100,
                        dataField: "contact",
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "联系方式",
                        width: 100,
                        dataField: "contactTel",
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户传真",
                        width: 100,
                        dataField: "fax",
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户邮编",
                        width: 100,
                        dataField: "zip",
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "创建日期",
                        dataField: "createDateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核状态",
                        dataField: "applyStatusDesc",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    /* ----------wangcan:增加同步CRM状态--------- */
                    {
                        type: "",
                        name: "同步CRM状态",
                        dataField: "applyStatusDesc",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户税号",
                        dataField: "taxCode",
                        width: 100,
                        isFixed: false,
                        toSort: false,
                        sortType: "",
                        isShow: $scope.isJCHK,
                    },
                    {
                        name: "客户组",
                        dataField: "customerGroup",
                        width: 100,
                        isFixed: false,
                        isShow: true,
                    },
                    {
                        name: "客户组描述",
                        dataField: "customerGroupDesc",
                        width: 120,
                        isFixed: false,
                        isShow: true,
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 260,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };

            $scope.vehTbConf = {
                fixedWidth: 120,
                scrollWidth: 1660,
                tableCol: [
                    {
                        type: "",
                        name: "客户",
                        width: 150,
                        dataField: "clientName",
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "品牌",
                        width: 100,
                        dataField: "brandName",
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "机型",
                        width: 100,
                        dataField: "model",
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "车号",
                        width: 100,
                        dataField: "carNo",
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "整机赠送额度（保养）",
                        width: 150,
                        dataField: "maintenanceSendAmount",
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "整机赠送额度（通用）",
                        width: 150,
                        dataField: "universalSendAmount",
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "系统已用额度（保养）",
                        width: 150,
                        dataField: "maintenanceUseAmount",
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "初始已用额度（保养）",
                        width: 150,
                        dataField: "initialMaintenanceUseAmount",
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "系统已用额度（通用)",
                        width: 150,
                        dataField: "universalUseAmount",
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "初始已用额度（通用)",
                        width: 150,
                        dataField: "initialUniversalUseAmount",
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "剩余额度（保养）",
                        width: 150,
                        dataField: "maintenanceLaveAmount",
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "剩余额度（通用）",
                        width: 150,
                        dataField: "universalLaveAmount",
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "是否停用",
                        width: 100,
                        dataField: "isDisableShow",
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "保修状态",
                        width: 100,
                        dataField: "warrantyStatusF",
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "备注",
                        dataField: "remark",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 120,
                        isShow: true,
                        isFixed: true,
                    }
                ]
            };

            $scope.receiveInfoTbConf = {
                fixedWidth: 100,
                scrollWidth: 1220,
                tableCol: [{
                        type: "",
                        name: "收货人",
                        width: 100,
                        dataField: "receiverName",
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "收货地址编码",
                        width: 100,
                        dataField: "addressCode",
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "收货地址",
                        width: 300,
                        dataField: "address",
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "联系方式",
                        width: 100,
                        dataField: "phone",
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 150,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };

            var btnPermissionCode = {
                clientAdd: window.ActionCode.clientAdd,
                clientSynCRM: window.ActionCode.clientSynCRM,
                clientDel: window.ActionCode.clientDel,
                clientEdit: window.ActionCode.clientEdit,
                clientInvite: window.ActionCode.clientInvite,
                clientUpdate: window.ActionCode.clientUpdate,
                clientBound: window.ActionCode.clientBound,
                clientImport: window.ActionCode.clientImport,
                clientReceiveInfo: window.ActionCode.clientReceiveInfo,
                clientVehicleAdd: window.ActionCode.clientVehicleAdd
            };

            $scope.btnPermission = {
                clientAdd: true,
                clientSynCRM: true,
                clientDel: true,
                clientEdit: true,
                clientInvite: true,
                clientUpdate: true,
                clientBound: true,
                clientImport: true,
                clientReceiveInfo: true,
                clientVehicleAdd: true
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            var oldVehicleDetail = {}; // 编辑客户车辆详情时详情的初始值

            $scope.bound = function () {
                $scope.changeTab(2);
            };

            $scope.getInfo = function (isValid) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                var service = 'device';
                var reqUrl = '/company/itemByInvitation';
                ybHttp.Get(service, reqUrl, $scope.boundObj).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.orgInfo = resp.value;
                })
            };
            $scope.doBound = function (isValid) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                var service = "device";
                var reqUrl = "/companyDealer/bound";
                ybHttp.Post(service, reqUrl, $scope.boundObj).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList();
                    $scope.changeTab(0);
                })
            };

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    scrollLeft: { left: $scope.tbConf.fixedWidth + "px" },
                    scrollLeftWidth: { width: $scope.tbConf.fixedWidth + "px" },
                };
                $scope.receiveInfoTbStyle = {
                    scrollLeft: {
                        left: $scope.receiveInfoTbConf.fixedWidth + "px"
                    }
                };
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    default:
                        break;
                }
            };
            $scope.invite = function (id) {
                var service = "device";
                var reqUrl = "/companyDealer/invite";
                ybHttp.Post(service, reqUrl, {
                    id: id
                }).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowMessage('邀请码为' + resp.value, MESG_TYPE.Success);
                });
            };

            $scope.dataSelected = {
                department: {},
                countryObj: { ids: [] }
            };

            function initData() {
                $scope.tabFlag = {};
                $scope.receiveInfoTabFlag = {};
                $scope.boundObj = {};
                $scope.dealerClass = {};
                $scope.detailInfo = {
                    locked: 0,
                    bigClientFlag: 0,
                    isStorage: 0,
                    normalFlag: 1
                };
                $scope.receiveInfo = {};
                $scope.dataSelected = {
                    department: {},
                    countryObj: { ids: [] }
                };
            }

            function getDataList(curPage) {
                var service = "device";
                var reqUrl = "/companyDealer/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = $scope.condition;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.markInfo.allChecked = false;
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.createDateShow = $filter("YbDate")(item.createDate);
                        item.normalFlagOld = item.normalFlag;
                        item.normalFlagF = $filter("CompanyDealerStatus")(item.normalFlag);
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            function getReceiveInfoDataList(curPage) {
                var service = "device";
                var reqUrl = "/companyDealer/listClientReceiverInfo";
                var param = {};
                param.pageSize = $scope.receiveInfoPageInfo.pageSize;
                if (!!curPage) {
                    $scope.receiveInfoPageInfo.curPage = curPage;
                }
                param.pageNum = $scope.receiveInfoPageInfo.curPage;
                param.filters = $scope.receiveInfoCondition;
                param.filters.dealerOrgId = $scope.dealerOrgId;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.markInfo.allChecked = false;
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.createDateShow = $filter("YbDate")(item.createDate);
                    });
                    $scope.receiveInfoPageInfo.totalRows = resp.value.total;
                    $scope.receiveInfoPageInfo.totalPages = resp.value.pages;
                    $scope.receiveInfoDataList = resp.value.list;
                });
            }

            $scope.toSort = function (config, index) {
                ybWidget.ToSort(config, index);
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.cueRow = index
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.receiveInfoSearch = function (curpage) {
                getReceiveInfoDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = { allQueryFlag: true };
            };

            $scope.receiveInfoReset = function () {
                $scope.receiveInfoCondition = {};
            };

            $scope.selectAll = function () {
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    $scope.dataList[i].isChecked = $scope.markInfo.allChecked;
                }
            };

            function checkAll() {
                var selectAll = false;
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    if (!$scope.dataList[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.updateCRM = function () {
                ybWidget.ShowMessage("确认从SAP下载数据吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/companyDealer/getSap";
                    ybHttp.Get(service, reqUrl).then(function () {})
                    ybWidget.ShowMessage("正在后台同步请稍后", MESG_TYPE.Note);
                }, function () {

                });
            };

            $scope.selectSingle = function (item) {
                if (!item.isChecked) {
                    $scope.markInfo.allChecked = false;
                } else {
                    if (!checkAll()) {
                        $scope.markInfo.allChecked = false;
                    } else {
                        $scope.markInfo.allChecked = true;
                    }
                }
            };

            $scope.addData = function () {
                $scope.tabFlag.type = 0;
                $scope.tabFlag.name = tabFlag[0];
                getClientLevel();
                $scope.changeTab(1);
            };

            $scope.synCRMClient = function () {
                ybWidget.ShowMessage("确认从CRM同步数据吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/companyDealer/syncProductAccountData";
                    ybHttp.Get(service, reqUrl).then(function () {})
                    ybWidget.ShowMessage("正在后台同步请稍后", MESG_TYPE.Note);
                }, function () {});
            };

            $scope.receiveInfoAddData = function () {
                $scope.receiveInfoTabFlag.type = 0;
                $scope.receiveInfoTabFlag.name = receiveInfoTabFlag[0];

                $scope.changeTab(4);
            };

            function getClientLevel() {
                var service = "device";
                var reqUrl = "/dealerLevel/list";
                var param = {};

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.detailInfo.clientLevelOption = resp.value;
                });
            }

            $scope.delData = function (delType, id) {
                var service = "device";
                var reqUrl = "/companyDealer/remove";
                var param = {};
                param.ids = [];
                if (delType === "single") {
                    param.ids.push(id);
                }
                if (delType === "batch") {
                    for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                        if (!!$scope.dataList[i].isChecked) {
                            param.ids.push($scope.dataList[i].id);
                        }
                    }
                    if (param.ids.length === 0) {
                        ybWidget.ShowMessage('请选择需要删除的行');
                        return;
                    }
                }
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    })
                }, function () {

                })
            };

            $scope.delReceiveInfoData = function (id) {
                var service = "device";
                var reqUrl = "/companyDealer/deleteClientReceiverInfo";
                var param = {};
                param.id = id;
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getReceiveInfoDataList();
                    })
                }, function () {

                })
            };
            $scope.getClientReceiverInfo = function (id) {
                var service = "device";
                var reqUrl = "/companyDealer/getClientReceiverInfo";
                var param = {
                    id: id
                };
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.receiveInfo = resp.value;
                })
            };
            $scope.updateReceiveInfoData = function (id) {
                $scope.receiveInfoTabFlag.type = 1;
                $scope.receiveInfoTabFlag.name = receiveInfoTabFlag[1];
                $scope.getClientReceiverInfo(id);
                $scope.changeTab(4);
            };

            $scope.editData = function (item) {
                $scope.dealerClass = {
                    className: item.dealerClassName,
                    id: item.dealerClassId
                };
                $scope.detailInfo = JSON.parse(JSON.stringify(item));
                $scope.changeTab(1);
                $scope.tabFlag.type = 1;
                $scope.tabFlag.name = tabFlag[1];
                $scope.dataSelected.department.id = item.deptId;
                $scope.dataSelected.department.departName = item.deptName;
                $scope.dataSelected.countryObj.ids = item.associateCountryVOS?.map(rva => rva.countryCode) || [];
                getClientLevel();
            };

            $scope.receiveInfoEditData = function (item) {
                $scope.dealerClass = {
                    className: item.dealerClassName,
                    id: item.dealerClassId
                };
                $scope.receiveInfo = item;
                $scope.changeTab(4);
                $scope.receiveInfoTabFlag.type = 1;
                $scope.receiveInfoTabFlag.name = receiveInfoTabFlag[1];
            };

            $scope.receiveInfoList = function (item) {
                $scope.dealerOrgId = item.dealerOrgId;
                getReceiveInfoDataList();
                $scope.changeTab(3);
                $scope.receiveInfoTabFlag.type = 0;
                $scope.receiveInfoTabFlag.name = receiveInfoTabFlag[0];
            };

            $scope.saveData = function (isValid) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                var service = "device";
                var reqUrl = "/companyDealer/insert";
                if ($scope.tabFlag.type === 1) {
                    reqUrl = "/companyDealer/update";
                }
                $scope.detailInfo.dealerClassId = $scope.dealerClass.id;
                $scope.detailInfo.deptId = $scope.dataSelected.department.id;

                // 通过客户分级字段的value,来获取label
                for (var i = 0; i < $scope.detailInfo.clientLevelOption.length; i++) {
                    if ($scope.detailInfo.clientLevelOption[i].id === $scope.detailInfo.dealerLevelId) {
                        $scope.detailInfo.dealerLevelName = $scope.detailInfo.clientLevelOption[i].levelName;
                    }
                }

                ybHttp.Post(service, reqUrl, $scope.detailInfo).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                });
            };


            // 保存客户车辆信息
            $scope.saveVehData = function (isValid, form) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                if ($scope.vehTabFlag.type !== 1) {
                    var totalAmount = parseFloat($scope.vehObj.maintenanceSendAmount || 0);
                    if (parseFloat($scope.vehObj.maintenanceSendAmount || 0) !=
                        (parseFloat($scope.vehObj.maintenanceUseAmount || 0) +
                            parseFloat($scope.vehObj.initialMaintenanceUseAmount || 0) +
                            parseFloat($scope.vehObj.maintenanceLaveAmount || 0))) {
                        ybWidget.ShowMessage("保养额度不平衡", MESG_TYPE.Error);
                        return;
                    }
                    if (parseFloat($scope.vehObj.universalSendAmount || 0) !=
                        (parseFloat($scope.vehObj.universalUseAmount || 0) +
                            parseFloat($scope.vehObj.initialUniversalUseAmount || 0) +
                            parseFloat($scope.vehObj.universalLaveAmount || 0))) {
                        ybWidget.ShowMessage("通用额度不平衡", MESG_TYPE.Error);
                        return;
                    }
                }
                var service = "device";
                var reqUrl = "/dealerVehicle/insert";
                if ($scope.vehTabFlag.type === 1) {
                    reqUrl = "/dealerVehicle/update";
                }

                ybHttp.Post(service, reqUrl, $scope.vehObj).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(5);
                    getMaintenVehList();
                });
            };

            $scope.receiveInfoSaveData = function (isValid) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                var service = "device";
                var reqUrl = "/companyDealer/saveClientReceiverInfo";
                $scope.receiveInfo.dealerOrgId = $scope.dealerOrgId;

                ybHttp.Post(service, reqUrl, $scope.receiveInfo).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(3);
                    getReceiveInfoDataList();
                    $scope.receiveInfo = {};
                });
            };

            $scope.cancelSaveData = function () {
                $scope.changeTab(3);
                $scope.receiveInfo = {};
            };

            // 获取机型列表
            function getModelList() {
                var url = '/commonMaintenance/queryModelList';
                ybHttp.Get('device', url).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    $scope.modelList = res.value;
                })
            }

            // 点击维护车辆
            $scope.maintenVeh = function (item) {
                $scope.changeTab(5);
                $scope.vehObj.clientName = item.companyName;
                $scope.vehObj.clientId = item.id;
                getMaintenVehList();

            };

            $scope.getMaintenVehList = function () {
                getMaintenVehList();
            };

            // 获取客户车辆列表
            function getMaintenVehList() {
                var service = "device";
                var reqUrl = "/dealerVehicle/list";
                var param = {};
                param.pageSize = $scope.maintenVehPageInfo.pageSize;
                /*if (!!curPage) {
                    $scope.maintenVehPageInfo.curPage = curPage;
                }*/
                param.pageNum = $scope.maintenVehPageInfo.curPage;
                param.filters = $scope.vehCondition;
                param.filters.clientName = $scope.vehObj.clientName;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.markInfo.allChecked = false;
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.createDateShow = $filter("YbDate")(item.createDate);
                        item.isDisableShow = $filter("TrueOrFalse")(item.isDisable);
                        item.warrantyStatusF = $filter("VehStatus")(item.warrantStatus);
                    });
                    $scope.maintenVehPageInfo.totalRows = resp.value.total;
                    $scope.maintenVehPageInfo.totalPages = resp.value.pages;
                    $scope.maintenVehList = resp.value.list;
                });
            }

            // 改变本次增加整机赠送额度（保养）的值
            $scope.changeMaintenance = function () {
                var updateAmount = parseFloat($scope.vehObj.maintenanceUpdateAmount || 0);
                var totalAmount = parseFloat(oldVehicleDetail.maintenanceSendAmount || 0);
                var restAmount = parseFloat(oldVehicleDetail.maintenanceLaveAmount || 0);

                $scope.vehObj.maintenanceSendAmount = ybWidget.Plus(totalAmount, updateAmount);
                $scope.vehObj.maintenanceLaveAmount = ybWidget.Plus(restAmount, updateAmount);
            };

            // 改变本次增加整机赠送额度（通用）的值
            $scope.changeUniversal = function () {
                var updateAmount = parseFloat($scope.vehObj.universalUpdateAmount || 0);
                var totalAmount = parseFloat(oldVehicleDetail.universalSendAmount || 0);
                var restAmount = parseFloat(oldVehicleDetail.universalLaveAmount || 0);

                $scope.vehObj.universalSendAmount = ybWidget.Plus(totalAmount, updateAmount);
                $scope.vehObj.universalLaveAmount = ybWidget.Plus(restAmount, updateAmount);
            };
            // 初始保养
            $scope.changeInitialMaintenance = function () {
                if ($scope.vehTabFlag.type !== 1) {
                    return;
                }
                var updateAmount = parseFloat($scope.vehObj.initialMaintenanceUseAmount || 0);
                var totalAmount = parseFloat($scope.vehObj.maintenanceSendAmount || 0);
                var useAmount = parseFloat($scope.vehObj.maintenanceUseAmount || 0);

                $scope.vehObj.maintenanceLaveAmount = totalAmount - updateAmount - useAmount;
                if ($scope.vehObj.maintenanceLaveAmount < 0) {
                    $scope.vehObj.maintenanceLaveAmount = 0;
                    $scope.vehObj.initialMaintenanceUseAmount = totalAmount - useAmount;
                }
            };

            // 初始通用
            $scope.changeInitialUniversa = function () {
                if ($scope.vehTabFlag.type !== 1) {
                    return;
                }
                var updateAmount = parseFloat($scope.vehObj.initialUniversalUseAmount || 0);
                var totalAmount = parseFloat($scope.vehObj.universalSendAmount || 0);
                var useAmount = parseFloat($scope.vehObj.universalUseAmount || 0);

                $scope.vehObj.universalLaveAmount = totalAmount - updateAmount - useAmount;
                if ($scope.vehObj.universalLaveAmount < 0) {
                    $scope.vehObj.universalLaveAmount = 0;
                    $scope.vehObj.initialUniversalUseAmount = totalAmount - useAmount;
                }
            };

            $scope.addVeh = function () {
                $scope.vehTabFlag.type = 0;
                $scope.vehTabFlag.name = tabFlag[0];
                $scope.vehObj = {
                    clientName: $scope.vehObj.clientName,
                    isDisable: 0,
                    clientId: $scope.vehObj.clientId,
                    warrantStatus: 1
                };
                $scope.changeTab(6);
            };

            $scope.editVehData = function (item) {
                $scope.vehTabFlag.type = 1;
                $scope.vehTabFlag.name = tabFlag[1];
                oldVehicleDetail = {};
                getVehDataItem(item.id);
                $scope.changeTab(6);
            };

            // 删除客户车辆
            $scope.deleteVehData = function (item) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    deleteVehicle([item.id]);
                });
            };

            function deleteVehicle(ids) {
                var url = "/dealerVehicle/remove";
                ybHttp.Post('device', url, ids).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getMaintenVehList();
                })
            }

            function getVehDataItem(id) {
                var service = "device";
                var reqUrl = "/dealerVehicle/detail";
                var param = {
                    id: id
                };

                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    oldVehicleDetail = angular.copy(resp.value);
                    $scope.vehObj = resp.value;
                })
            }

            // 车辆列表点击停用
            $scope.stop = function (id) {
                ybWidget.ShowMessage("确定要停用吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/dealerVehicle/disable";
                    var param = {
                        id: id,
                        isDisable: $scope.isOrNotEnum.Is
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getMaintenVehList();
                    })
                }, function () {

                })
            };

            $scope.importDealer = function () {
                var param = {
                    name: "客戶",
                    templateReqService: "device",
                    templateReqUrl: "/companyDealer/downloadDealerExcel",
                    importReqService: "device",
                    importReqUrl: "/companyDealer/importDealerExcel",
                    importErrorUrl: ""
                };
                ybWidget.ImportFile(param).then(function (data) {
                    getDataList(1);
                });
            };

            $scope.importVeh = function () {
                var param = {
                    name: "客户车辆",
                    templateReqService: "device",
                    templateReqUrl: "/dealerVehicle/downloadImportExcel",
                    importReqService: "device",
                    importReqUrl: "/dealerVehicle/importVehicleExcel",
                    importErrorUrl: "",
                };
                ybWidget.ImportFile(param).then(function (data) {
                    getMaintenVehList();
                });
            };

            $scope.importClientMaterials = function () {
                var param = {
                    name: "客户零件",
                    templateReqService: "device",
                    templateReqUrl: "/dealerRelationMaterial/materialsTempDown",
                    importReqService: "device",
                    importReqUrl: "/dealerRelationMaterial/importMaterials",
                    importErrorUrl: "",
                };
                ybWidget.ImportFile(param).then(function (data) {
                    getMaintenVehList();
                });
            };

            $scope.viewClientMaterials = function(item) {
                ybWidget.DataSelector({
                    title: '客户零件',
                    url: '/dealerRelationMaterial/list',
                    otherParams: { dealerCode: item.dealerCode },
                    keyWords: [{label: '零件编号', field: 'materialNo'}],
                    fields: [
                        {
                            name: '零件编号',
                            dataField: 'materialNo',
                            width: "30%"
                        },
                        {
                            name: '零件中文名',
                            dataField: 'materialDes',
                            width: "70%"
                        }
                    ],
                    isOnlyShow: true
                })
            };

            $scope.selectWarehouse = function () {
                let param={'multy':true};
                ybWidget.WarehouseSelector(param).then(function (data) {
                    $scope.detailInfo.forwardWarehouseCode = param['multy']?data:
                        data.warehouseCode;
                })
            };

            $scope.clearWarehouse = function () {
                $scope.detailInfo.forwardWarehouseCode = null;
            };

            $scope.restAdminPwd = function (item) {
                ybWidget.ShowMessage("确定将超管的密码重置为xcmg123.吗？", MESG_TYPE.Ask).then(function () {
                    var service = "auth";
                    var reqUrl = "/auth/resetAdminPasswordByOrgId";
                    var param = {
                        orgId: item.platOrgId
                    }
                    ybHttp.Get(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                    });
                }, function () {

                });
            };

            $scope.switchStopStatus = function (item, stopType) {
                var reqUrl = "/companyDealer/unbind";
                var tipMsg = "停用";
                if (stopType == 0) {
                    tipMsg = "启用";
                    reqUrl = "/companyDealer/bind";
                }

                var param = {
                    id: item.id,
                    orgId: item.orgId
                }
                ybWidget.ShowMessage("确定" + tipMsg + "该用户吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post("device", reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                }, function () {

                });
            };

            (function () {
                getDataList();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
                getModelList();
            })();
        }]);
})(window, window.angular);
